﻿using HandyControl.Controls;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Walterlv.Demo.Interop;
using Window = System.Windows.Window;
using NotifyIcon = System.Windows.Forms.NotifyIcon;
using ContextMenu = System.Windows.Forms.ContextMenu;
using MenuItem = System.Windows.Forms.MenuItem;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Security.AccessControl;

namespace 倒计时
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static List<string[]> Listitem = new List<string[]>();
        private static NotifyIcon n1;
        public MainWindow()
        {
            InitializeComponent();

            Setting.Add += Setting_Add;
            Setting.Change += Setting_Change;
            Setting.TopMost1 += Setting_TopMost1;

            WindowBlur.SetIsEnabled(this, true);
            Task.Run(() =>
            {
                JObject root = JObject.Parse(File.ReadAllText("App.json"));
                if (!root["debug"].ToString().Equals("true"))
                    RunAtStart();
                GetUpdate("1.0", "20220422");
                LoadColor(root["colormode"].ToString());
                n1 = new NotifyIcon()
                {
                    Icon = System.Drawing.Icon.ExtractAssociatedIcon("icon.ico"),

                }; n1.Visible = true;
                ContextMenu c1 = new ContextMenu();

                MenuItem ct1 = new MenuItem() { Text = "退出", Name = "exit" }; ct1.Click += Ct1_Click;
                c1.MenuItems.Add(ct1);
                MenuItem ct5 = new MenuItem() { Text = "程序设置", Name = "setting" }; ct5.Click += Ct1_Click;
                c1.MenuItems.Add(ct5);
                MenuItem ct2 = new MenuItem() { Text = "恢复窗口", Name = "resume" }; ct2.Click += Ct1_Click;
                c1.MenuItems.Add(ct2);
                MenuItem ct3 = new MenuItem() { Text = "隐藏窗口", Name = "minisize" }; ct3.Click += Ct1_Click;
                c1.MenuItems.Add(ct3);
                MenuItem ct4 = new MenuItem() { Text = "置顶窗口模式切换", Name = "topmost" }; ct4.Click += Ct1_Click;
                c1.MenuItems.Add(ct4);
                MenuItem ct6 = new MenuItem() { Text = "禁止移动窗口模式切换", Name = "notmove" }; ct6.Click += Ct1_Click;
                c1.MenuItems.Add(ct6);
                n1.ContextMenu = c1;
                n1.Click += N1_Click;
                GC.Collect();
                System.Windows.Forms.Application.Run();
            });
            Reload();

            //Screen s1 = new Screen();
            //s1.Show();

            GC.Collect();
        }

        private void N1_Click(object sender, EventArgs e)
        {
            WebClient wc = new WebClient();
            JObject root = JObject.Parse(Encoding.UTF8.GetString(wc.DownloadData("https://v1.jinrishici.com/all")));
            n1.ShowBalloonTip(300, "《" + root["origin"] + "》 作者 " + root["author"], root["content"].ToString(),ToolTipIcon.Info);
            wc.Dispose();
            GC.Collect();
        }

        private void Ct1_Click(object sender, EventArgs e)
        {
            switch (((MenuItem)sender).Name)
            {
                case "exit":
                    Environment.Exit(0);
                    break;
                case "resume":
                    Dispatcher.Invoke(new Action(
                               delegate
                               {
                                   Visibility = Visibility.Visible;
                               }));
                    break;
                case "minisize":
                    Dispatcher.Invoke(new Action(
                               delegate
                               {
                                   Visibility = Visibility.Collapsed;
                               }));
                    break;
                case "topmost":
                    Setting_TopMost1(true);
                    break;
                case "setting":
                    Dispatcher.Invoke(new Action(
                               delegate
                               {
                                   Setting set1 = new Setting();
                                   set1.Show();
                               }));
                    break;
                case "notmove":
                    NotMove();
                    break;
            };
        }

        #region 开机自启动写入注册表

        private void RunAtStart()
        {
            string starupPath = GetType().Assembly.Location;
            try
            {
                string fileName = starupPath;
                string shortFileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
                //打开子键节点
                RegistryKey myReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree,RegistryRights.FullControl);
                if (myReg.Equals(null))
                {
                    myReg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                if (!myReg.Equals(null) && !myReg.GetValue(shortFileName).Equals(null))
                {
                    myReg.DeleteValue(shortFileName);
                    myReg.SetValue(shortFileName, fileName);
                }
                else if (!myReg.Equals(null) && myReg.GetValue(shortFileName).Equals(null))
                {
                    myReg.SetValue(shortFileName, fileName);
                }
            }
            catch { }
        }

        #endregion

        private bool canmove = true;

        private void NotMove()
        {
            if (canmove) canmove = false;
            else canmove = true;
        }

        private void Setting_TopMost1(bool light)
        {
            Dispatcher.Invoke(new Action(
                               delegate
                               {
                                   if (this.Topmost.Equals(true)) this.Topmost = false;
                                   else this.Topmost = true;
                                   Growl.SuccessGlobal("切换成功");
                               }));
            GC.Collect();
        }

        private void Setting_Add(bool light)
        {
            Listitem.Clear();
            Reload();
        }

        private void Reload()
        {
            JObject root = JObject.Parse(File.ReadAllText("App.json"));
            choose.Items.Clear();
            foreach (JObject jObject in JArray.Parse(root["items"].ToString()))
            {
                try
                {
                    DateTime t0 = DateTime.Parse(DateTime.Now.ToShortDateString());
                    DateTime t1 = DateTime.Parse(jObject["time"].ToString());
                    string timetxt = (t1 - t0).ToString();
                    string[] str = { timetxt.Remove(timetxt.IndexOf(".")) + "天", "距离 " + jObject["title"].ToString() + " 剩余" };
                    Listitem.Add(str);
                    choose.Items.Add(jObject["title"].ToString());
                    if (t1.Date.Equals(0)) Growl.InfoGlobal("事件 " + jObject["title"] + " 到日期啦!");
                    GC.Collect();
                }
                catch (Exception ex)
                {
                    if (root["debug"].ToString().Equals("true")) Growl.ErrorGlobal("程序出现错误\n" + ex.ToString());
                    else Growl.ErrorGlobal("程序出现错误\n" + ex.Message);
                    GC.Collect();
                }
            }
            choose.SelectedIndex = 0;
        }

        private void LoadColor(string txt)
        {
            Color BlackBackground = Color.FromArgb(76, 101, 101, 101);
            Color BlackText = Color.FromArgb(255, 0, 0, 0);
            Color WhiteText = Color.FromArgb(255, 255, 255, 255);
            Color WhiteBackground = Color.FromArgb(153, 255, 255, 255);
            if (txt.Equals("light"))
            {
                Dispatcher.Invoke(new Action(
                               delegate
                               {
                                   Background = new SolidColorBrush(WhiteBackground);
                                   time.Foreground = new SolidColorBrush(BlackText);
                               }));
                GC.Collect();
            }
            else
            {
                Dispatcher.Invoke(new Action(
                               delegate
                               {
                                   Background = new SolidColorBrush(BlackBackground);
                                   time.Foreground = new SolidColorBrush(WhiteText);
                               }));
                GC.Collect();
            }
        }

        private void Setting_Change(bool light)
        {
            Color BlackBackground = Color.FromArgb(76, 101, 101, 101);
            Color BlackText = Color.FromArgb(255, 0, 0, 0);
            Color WhiteText = Color.FromArgb(255, 255, 255, 255);
            Color WhiteBackground = Color.FromArgb(153, 255, 255, 255);
            if (light)
            {
                Background = new SolidColorBrush(WhiteBackground);
                time.Foreground = new SolidColorBrush(BlackText);
                GC.Collect();
            }
            else
            {
                Background = new SolidColorBrush(BlackBackground);
                time.Foreground = new SolidColorBrush(WhiteText);
                GC.Collect();
            }
        }

        public static void GetUpdate(string version,string date)
        {
            try
            {
                WebClient w1 = new WebClient();
                JObject root = JObject.Parse(Encoding.UTF8.GetString(w1.DownloadData("https://fbtstudio.gitee.io/webframwork/fstore/update.json")));
                if (!root["time"].ToString().Equals(date) || !root["version"].ToString().Equals(version))
                    Growl.InfoGlobal("程序有版本更新!请在设置页下载");
            }
            catch { }
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton.Equals(MouseButtonState.Pressed) && canmove) DragMove();
            else if (e.RightButton.Equals(MouseButtonState.Pressed))
            {
                this.Visibility = Visibility.Collapsed;
                n1.ShowBalloonTip(100, "Tips 提示", "倒计时最小化到这里来啦，需要关闭请右键我哦!", ToolTipIcon.Info);
            }
        }

        private void Choose_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string[] data = Listitem[choose.SelectedIndex];
                time.Text = data[0];
                title.Content = data[1];
                GC.Collect();
            }
            catch {
                time.Text = "";
                title.Content = "请先去设置进行初始化!";
                GC.Collect();
            }
        }

        private void Title_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Setting set1 = new Setting();
            set1.Show();
        }

        private void Title_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Setting set1 = new Setting();
            set1.Show();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            n1.Dispose();
        }
    }
}
